﻿namespace BEGDC.CC.Web.UserControls.EV
{
	using System;
	using System.Collections;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	using BEGDC.Utility.Castle;
	using BEGDC.Utility.ExceptionManagement;
	using BEGDC.CC.BL.Workflow;
	using BEGDC.CC.Entity;
	using BEGDC.CC.BL.Common;
	using BEGDC.CC.BL.Common.Query;

	/// <summary>
	///		Summary description for APAttachment.
	/// </summary>
	public class APAttachment : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.Button btnAttach;
		protected System.Web.UI.WebControls.TextBox txtDocRelativePath;
		protected System.Web.UI.WebControls.TextBox txtDocPath;
		protected System.Web.UI.WebControls.DataGrid dgAttachment;
		protected System.Web.UI.HtmlControls.HtmlTable tblBody;
		protected System.Web.UI.HtmlControls.HtmlInputFile AttachmentFile;
		protected System.Web.UI.WebControls.ImageButton btnSubmit;
		protected System.Web.UI.WebControls.Button ibtnSave;
		protected System.Web.UI.HtmlControls.HtmlTableRow tr_Attach;
		private bool IsView
		{
			get
			{
				string state = this.Request.QueryString["State"];
				if(state == null) return false;
				if(state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.End
					|| state == SysDicItem.ProjectStatusFlag.Pending)
					return true;
				else
					return false;
			}
		}
		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!Page.IsPostBack)
				BindAttachment();
			if(this.IsView)
			{
				this.tr_Attach.Visible = false;
			}
				
		}

		#region Web Form Designer generated code
		private void InitializeComponent()
		{
			this.ibtnSave.Click += new EventHandler(this.ibtnSave_Click);
			this.dgAttachment.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgAttachment_ItemCommand);
			this.dgAttachment.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgAttachment_ItemDataBound);
			this.Load += new System.EventHandler(this.Page_Load);

		}

		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		#endregion

		private void BindAttachment()
		{
			if( Request.QueryString["APID"] + string.Empty == string.Empty && Request.QueryString["APPId"] + string.Empty == string.Empty )
			{
				this.btnAttach.Visible = false;
			}
			DataTable table = null;
			IQuery query = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

			if(Request.QueryString["APID"] != null && Request.QueryString["APID"] != string.Empty)
				table = query.GetAttachmentByApId(Convert.ToInt32(Request.QueryString["APID"]));
			else
				table = query.GetAttachmentByAppId(Convert.ToInt32(Request.QueryString["APPId"]));
			this.dgAttachment.DataSource = table;
			this.dgAttachment.DataBind();
		}


		private void dgAttachment_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			try
			{
//				if(e.CommandName == "Download")
//				{
//					string file = e.Item.Cells[4].Text;
//					System.IO.FileStream fileStream = new System.IO.FileStream(file, System.IO.FileMode.Open); 
//					try
//					{
//						long fileSize = fileStream.Length; 
//						Context.Response.ContentType="application/octet-stream"; 
//						//中文文件名需要UTF8编码
//						string fileName = System.IO.Path.GetFileName(file).Substring(5);
//						Context.Response.AddHeader("Content-Disposition","attachment; filename=\"" + HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) + "\""); 
//						Context.Response.AddHeader("Content-Length",fileSize.ToString()); 
//						byte[] fileBuffer=new byte[fileSize]; 
//						fileStream.Read(fileBuffer, 0, (int)fileSize);
//			
//						Context.Response.BinaryWrite(fileBuffer); 
//						Context.Response.End();
//					}
//					finally
//					{
//						fileStream.Close();
//					}
//				}
//				else 
					if( e.CommandName == "Delete" )
				{
					string fileId = e.Item.Cells[0].Text;
					BEGDC.CC.BL.Common.IUtility utiService = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
					utiService.DeleteFileById( Convert.ToInt32( fileId ) ); 
					BindAttachment();
				}
			}			
			catch(Exception ex)
			{
				Response.Write("<script>alert(\"An error occured when doing the action\\r\\nPlease turn to Admin for help\")</script>");
			}
		}

		public void SetAttachVisible(bool isVisible)
		{
			this.tr_Attach.Visible = isVisible;
			this.dgAttachment.Columns[5].Visible = isVisible;
		}
		private void ibtnSave_Click(object sender, EventArgs e)
		{
			if (AttachmentFile.PostedFile == null || AttachmentFile.PostedFile.FileName + "" == "")
			{
				return;
			}
			else
			{
				string fileExt = "txt,ppt,doc,xls,pdf,rar,zip";
				string fileName = "";
				string appDocRoot = BEGDC.CC.BL.Workflow.Configuration.AttachmentPath;
				string fullPath;
				string strExt;
				
				string relativePath = WebUtility.GetDocumentStoredPath(appDocRoot, AttachmentFile.PostedFile.FileName, out fullPath);				

				fileName=System.IO.Path.GetFileName(fullPath).Substring(5);					
				//check if the file is allowed to be uploaded
				strExt = fileName.Substring(fileName.Length-3).ToUpper();
				if (fileExt.ToUpper().IndexOf(strExt)<0)
				{
					Page.RegisterClientScriptBlock("","<script>alert('This file is not allowed to be uploaded!')</script>");
					return;
				}

				AttachmentFile.PostedFile.SaveAs(fullPath);
				IUtility utiService = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
				Attachment attach = new Attachment();
				if(Request.QueryString["APID"] != null && Request.QueryString["APID"] != string.Empty)
				{
					attach.ActionPoint = new Entity.ActionPoint();
					attach.ActionPoint.Id = Convert.ToInt32(Request.QueryString["APId"]);
					attach.AttachmentType = utiService.GetDicItem( BEGDC.CC.BL.CCFlow.AttachmentType.OTHERS.ToString(), BEGDC.CC.BL.Common.DicType.ATTACHMENTTYPE );
				}
				else
				{
					attach.Application = new Application();
					attach.Application.Id = Convert.ToInt32(Request.QueryString["APPId"]);
				}

																										  
				attach.FileName = fileName;
				attach.FilePath = fullPath;
				attach.Date = System.DateTime.Now;
				attach.Owner = HttpContext.Current.User.Identity.Name;

				IUtility utilityService = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
				utilityService.SaveAttachment(attach);
				BindAttachment();
			}
		}

		private void dgAttachment_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
			{
				ImageButton btnEdit = (ImageButton) e.Item.Cells[5].FindControl("btnDelAttach");
				string ItemId = e.Item.Cells[0].Text.ToString();
				if(btnEdit != null)
				{
					btnEdit.Attributes.Add("onclick","return confirm('Are you sure to delete this item?');");
				}
				
			}

		}
	}
}
